/**   
 * @Title: PayBillController.java 
 * @Package cn.kxm.controller 
 * @Description: paybill的控制层
 * @author 初雨泽
 * @date 2018年9月27日 下午3:09:08   
 */
package cn.kxm.controller;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;

import cn.kxm.pojo.InstroageBill;
import cn.kxm.pojo.PayBill;
import cn.kxm.pojo.PayBillDetail;
import cn.kxm.service.InstroageBillService;
import cn.kxm.service.PayBillDetailService;
import cn.kxm.service.PayBillService;
import cn.kxm.util.ExcelUtil;
import cn.kxm.util.MakeNewCode;
import cn.kxm.util.WorderToNewWordUtils;

/** 
 * @ClassName: PayBillController 
 * @Description: paybill控制层
 * @author 初雨泽
 * @date 2018年9月27日 下午3:09:08 
 *  
 */
@Controller
@RequestMapping("payBillController")
@SessionAttributes(value= {"payCode","payBill"})
public class PayBillController {
	@Autowired
	private PayBillService payBillService;

	@Autowired
	private PayBillDetailService payBillDetailService;

	@Autowired
	private InstroageBillService instroageBillService;

	@Autowired
	private MakeNewCode makeNewCode;

	/** 
	 * @Title: reLoadDatagird 
	 * @Description: 显示paybill数据表
	 * @param page
	 * @param rows
	 * @param findcode
	 * @param findstartDate
	 * @param findendDate
	 * @param findsupplierName
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("reLoadDatagird")
	@ResponseBody
	public Object reLoadDatagird(@RequestParam(required=false) Integer page,
			@RequestParam(required=false)Integer rows,
			@RequestParam(required=false) String findcode,
			@RequestParam(required=false) String findstartDate,
			@RequestParam(required=false) String findendDate,
			@RequestParam(required=false) String findsupplierName) {
		System.out.println("reLoadData");
		if(page==null){
			return "success";
		}
		System.out.println("page:"+page);
		System.out.println("rows:"+rows);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", payBillService.searchPayBill(page, rows, findcode, findstartDate, findendDate, findsupplierName));
		map.put("total", payBillService.countSearchPayBill(findcode, findstartDate, findendDate, findsupplierName));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: beforeAddPayBill 
	 * @Description: 添加表单前的处理订单号方法
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("beforeAddPayBill")
	@ResponseBody
	public Object beforeAddPayBill() {
		System.out.println("beforeAddPayBill");
		Map<String,Object> map=new HashMap<String, Object>();
		String code=makeNewCode.getRandomCodeByPrefix("FK");
		map.put("code", code);
		System.out.println(code);
		return JSON.toJSON(map);
	}


	/** 
	 * @Title: findCompanyPayBill 
	 * @Description: 装载供应商数据表格
	 * @param page
	 * @param rows
	 * @param name
	 * @param code
	 * @param type
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("companyPayBill")
	@ResponseBody
	public Object findCompanyPayBill(Integer page,Integer rows,
			@RequestParam(value="name",required=false) String name,
			@RequestParam(value="code",required=false) String code,
			@RequestParam(value="type",required=false) Integer type) {
		System.out.println("name:"+name+"   code:"+code+"  type:"+type);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", payBillService.searchCompany(code, name, type, page, rows));
		map.put("total", payBillService.countSearchCompany(code, name, type));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: findPayBillDetail 
	 * @Description: 查询paybill并查询paybilldetail,通过detail查询入库单,并放入session
	 * @param payCode
	 * @param model
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("findPayBill")
	@ResponseBody
	public String findPayBillDetail(@RequestParam("payCode") String payCode,Model model) {
		System.out.println("findPayBill");
		model.addAttribute("payBill", payBillService.findPayBill(payCode));
		model.addAttribute("payCode", payCode);
		return "success";
	}

	/** 
	 * @Title: loadPayBillDetail 
	 * @Description: 装载paybill详情表单数据
	 * @param paybill
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadPayBill")
	@ResponseBody
	public Object loadPayBillDetail(@ModelAttribute("payBill") PayBill paybill,ModelMap model) {
		Map<String,Object> map=new HashMap<String, Object>();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
		String dateString = formatter.format(paybill.getPayDate());
		map.put("code", paybill.getCode());
		map.put("payDate", dateString);
		map.put("customName", paybill.getCustomName());
		map.put("type", paybill.getPayType());
		map.put("payTotalMoney", paybill.getPayTotalMoney());
		map.put("memo", paybill.getMemo());
		model.remove("payBill");
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: loadDetailInFirstPage 
	 * @Description: 在首页加载paybilldetail
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadDetailInFirstPage")
	@ResponseBody
	public Object loadDetailInFirstPage(@RequestParam("code") String code) {
		List<PayBillDetail> list=payBillDetailService.findPayBillDetail(code);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", list);
		return JSON.toJSON(map);
	}

	/** 
	 * @Title: loadInstroageListByPayBill 
	 * @Description: 加载paybill中的入库单
	 * @param list
	 * @param model
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadInstroageListByPayBill")
	@ResponseBody
	public Object loadInstroageListByPayBill(@ModelAttribute("payCode") String payCode,
			Integer page,Integer rows) {
		System.out.println("loadInstroageListByPayBill");
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", payBillDetailService.findPayBillDetail(payCode));
		/*map.put("total",instroageBillService.countInstroageBillByPayBillCode(payCode));*/
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: revokePayBill 
	 * @Description: 撤销审核状态
	 * @param code
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("revokePayBill")
	@ResponseBody
	public Object revokePayBill(@RequestParam("code") String code) {
		payBillService.updatePayBillType(code, 1);

		//
		List<PayBillDetail> list=payBillDetailService.findPayBillDetail(code);
		List<InstroageBill> instroageBillList=new ArrayList<InstroageBill>();
		for (PayBillDetail a:list) {
			System.out.println("a.getBillCode:"+a.getBillCode());
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				instroageBillList.add(instroageBillService.findPayBillDetail(billCode));
			}
			/*payBillDetailService.deleteRealMoneyByPayBillDetail(a.getId());*/
		}
		/*for(InstroageBill a:instroageBillList) {
			if(a!=null) {
				instroageBillService.updateInstroageBillType(a.getCode(), 1);
			}
		}*/
		System.out.println("successRevoke");
		String result="success";
		return result;
	}

	/** 
	 * @Title: loadUnselectedInstroageBill 
	 * @Description: 加载未被选择的入库单供paybill选择
	 * @return  参数说明 
	 * @return Object    返回类型 
	 * @throws 
	 */
	@RequestMapping("loadUnselectedInstroageBill")
	@ResponseBody
	public Object loadUnselectedInstroageBill(Integer page,Integer rows,
			@RequestParam(required=false) String findcode,
			@RequestParam(required=false) String findstartDate,
			@RequestParam(required=false) String findendDate,
			@RequestParam(required=false) String findsupplierName,
			@RequestParam(required=false) String payCode) {
		System.out.println("loadUnselectedInstroageBill");
		System.out.println("findcode:"+findcode+"findstartDate:"+findstartDate+"findendDate:"+findendDate+"findsupplierName:"+findsupplierName+"payCode:"+payCode);
		System.out.println("page:"+page);
		System.out.println("rows:"+rows);
		Map<String, Object> map=new HashMap<String, Object>();
		map.put("rows", instroageBillService.findUnselectedInstroageBill(page, rows, findcode, findstartDate, findendDate, findsupplierName,payCode));
		map.put("total", instroageBillService.countUnselectedInstroageBill(findcode, findstartDate, findendDate, findsupplierName,payCode));
		System.out.println(map);
		return JSON.toJSONString(map);
	}

	/** 
	 * @Title: savePayBillDetailToDataBase 
	 * @Description: 保存paybill和paybill 的入库单instroagebill
	 * @param data
	 * @param payCode
	 * @param payData
	 * @param payType
	 * @param memo
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("savePayBillDetailToDataBase")
	@ResponseBody
	public String savePayBillDetailToDataBase(@RequestParam("saveRows") String data,
			@RequestParam("payCode") String payCode,
			@RequestParam("payData") String payData,
			@RequestParam("payType") String payType,
			@RequestParam("memo") String memo,
			@RequestParam("payTotalMoney") String payTotalMoney) {
		System.out.println("savePayBillDetailToDataBase");
		System.out.println("payTotal:"+payTotalMoney);
		//处理instroagebill部分
		List<PayBillDetail> list=(List<PayBillDetail>) JSONArray.parseArray(data, PayBillDetail.class);
		/*List<PayBillDetail> list_detail=new ArrayList<PayBillDetail>();
		for(int i=0;i<list.size();i++) {
			PayBillDetail p=new PayBillDetail();
			p.setBillCode(list.get(i).getCode());
			p.setMemo(list.get(i).getMemo());
			p.setPayCode(payCode);
			p.setPayMoney(list.get(i).getMoney());
			p.setRealMoney(0.00);
			list_detail.add(p);
		}*/
		payBillDetailService.deleteDetailListByPayBill(payCode);
		payBillDetailService.addDetailListByPayBill(list,payCode);
		//处理表单部分
		System.out.println("payType"+payType);
		Integer payType_i=Integer.parseInt(payType);
		Float payTotalMoney_f=Float.parseFloat(payTotalMoney);
		payBillService.updatePayBill(payData, payType_i, memo, payCode, payTotalMoney_f);
		return "success";
	}

	/** 
	 * @Title: payCurrentPayBill 
	 * @Description: 未支付paybill的审核方法
	 * @param code
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("payCurrentPayBill")
	@ResponseBody
	public String payCurrentPayBill(@RequestParam("code") String code) {
		System.out.println("payCurrentPayBill");
		payBillService.updatePayBillType(code, 2);
		List<PayBillDetail> list=payBillDetailService.findPayBillDetail(code);
		List<InstroageBill> instroageBillList=new ArrayList<InstroageBill>();
		for (PayBillDetail a:list) {
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				instroageBillList.add(instroageBillService.findPayBillDetail(billCode));
			}
			/*payBillDetailService.addRealMoneyByPayBillDetail(a.getId());*/
		}
		/*for(InstroageBill a:instroageBillList) {
			if(a!=null) {
				instroageBillService.updateInstroageBillType(a.getCode(), 2);
			}
		}*/
		System.out.println("successCheck");
		String result="success";
		return result;
	}

	/** 
	 * @Title: realPayCurrentBill 
	 * @Description: 支付方法
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("realPayCurrentBill")
	@ResponseBody
	public String realPayCurrentBill(@RequestParam("code") String code) {
		System.out.println("payCurrentPayBill");
		payBillService.updatePayBillType(code, 3);
		List<PayBillDetail> list=payBillDetailService.findPayBillDetail(code);
		List<InstroageBill> instroageBillList=new ArrayList<InstroageBill>();
		for (PayBillDetail a:list) {
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				instroageBillList.add(instroageBillService.findPayBillDetail(billCode));
			}
			payBillDetailService.addRealMoneyByPayBillDetail(a.getId());
		}
		for(InstroageBill a:instroageBillList) {
			if(a!=null) {
				instroageBillService.updateInstroageBillType(a.getCode(), 2);
				instroageBillService.updatePurchasePayStatus(instroageBillService.findOrderCodeFromInstroDetail(a.getCode()),2);
			}
		}
		System.out.println("successPay");
		String result="success";
		return result;
	}

	/** 
	 * @Title: revokeRealPayCurrentBill 
	 * @Description: 撤销支付方法
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("revokeRealPayCurrentBill")
	@ResponseBody
	public String revokeRealPayCurrentBill(@RequestParam("code") String code) {
		payBillService.updatePayBillType(code, 2);

		//
		List<PayBillDetail> list=payBillDetailService.findPayBillDetail(code);
		List<InstroageBill> instroageBillList=new ArrayList<InstroageBill>();
		for (PayBillDetail a:list) {
			System.out.println("a.getBillCode:"+a.getBillCode());
			if(a.getBillCode()!="") {
				String billCode=a.getBillCode();
				instroageBillList.add(instroageBillService.findPayBillDetail(billCode));
			}
			payBillDetailService.deleteRealMoneyByPayBillDetail(a.getId());
		}
		for(InstroageBill a:instroageBillList) {
			if(a!=null) {
				instroageBillService.updateInstroageBillType(a.getCode(), 1);
				instroageBillService.updatePurchasePayStatus(instroageBillService.findOrderCodeFromInstroDetail(a.getCode()),1);
			}
		}
		System.out.println("successRevoke");
		String result="success";
		return result;
	}

	/** 
	 * @Title: addPayBill 
	 * @Description: 添加一个paybill
	 * @param code
	 * @param payDate
	 * @param customName
	 * @param payType
	 * @param payTotalMoney
	 * @param memo
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("addPayBill")
	@ResponseBody
	public String addPayBill(@RequestParam("code") String code,
			@RequestParam("payDate") String payDate,
			@RequestParam("customName") String customName,
			@RequestParam("payType") String payType,
			@RequestParam("payTotalMoney") String payTotalMoney,
			@RequestParam("memo") String memo) {
		System.out.println("addPayBill");
		PayBill newPayBill=new PayBill();
		newPayBill.setCode(code);
		newPayBill.setCustomName(customName);
		newPayBill.setMemo(memo);
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		Date date=null;
		try {
			date=format.parse(payDate);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		newPayBill.setPayDate(date);
		newPayBill.setPayTotalMoney(Double.parseDouble(payTotalMoney));
		newPayBill.setPayType(Integer.parseInt(payType));
		payBillService.addPayBill(newPayBill);
		return "success";
	}

	/** 
	 * @Title: deletePayBill 
	 * @Description: 删除payBill
	 * @param code
	 * @param payStatus
	 * @return  参数说明 
	 * @return String    返回类型 
	 * @throws 
	 */
	@RequestMapping("deletePayBill")
	@ResponseBody
	public String deletePayBill(@RequestParam("payCode") String code,
			@RequestParam("payStatus") String payStatus) {
		System.out.println("deletePayBill");
		Integer payStatus_i=Integer.parseInt(payStatus);
		if(payStatus_i==1) {
			//未付款
			payBillService.deletePayBillUnchecked(code);
		}else {
			//已付款
			payBillService.deletePayBillChecked(code);
		}
		return "success";
	}

	/** 
	 * @Title: export 
	 * @Description: 生成excel文件
	 * @param request
	 * @param response
	 * @throws Exception  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	@RequestMapping("getExcel")
	public void export(HttpServletRequest request,HttpServletResponse response,
			@RequestParam("findcode") String findcode,
			@RequestParam("findstartDate") String findstartDate,
			@RequestParam("findendDate") String findendDate,
			@RequestParam("findsupplierName") String findsupplierName) throws Exception {
		//获取数据
		List<PayBill> list=payBillService.findAllPayBill(findcode,
				findstartDate,
				findendDate,
				findsupplierName);
		/*List<PayBill> list=new ArrayList<PayBill>();
		for(int i=0;i<2;i++) {
			PayBill p=new PayBill();
			p.setCode(String.valueOf(i));
			p.setCustomName("qwe");
			p.setMemo("123");
			p.setPayDate(new Date());
			p.setPayStatus(1);
			p.setPayTotalMoney(2);
			p.setPayType(2);
			list.add(p);
		}*/
		System.out.println(list);

		//excel标题
		String[] title= {"付款单号","付款日期","单位名称","付款金额","付款方式","支付状态","备注"};
		System.out.println(title);

		//excel文件名
		String fileName="采购付款管理"+new Date()+".xls";
		System.out.println(fileName);

		//sheet名
		String sheetName="采购付款管理";
		System.out.println(sheetName);

		//装载数据
		String[][] content=new String[list.size()][title.length];
		for(int i=0;i<list.size();i++) {
			PayBill p=list.get(i);
			content[i][0]=p.getCode();
			content[i][1]=(p.getPayDate()).toString();
			content[i][2]=p.getCustomName();
			content[i][3]=String.valueOf(p.getPayTotalMoney());
			if(p.getPayType()==1) {
				content[i][4]="现金";
			}else {
				content[i][4]="转账";
			}
			if(p.getPayStatus()==1) {
				content[i][5]="未审核";
			}else if(p.getPayStatus()==2){
				content[i][5]="已审核";
			}else if(p.getPayStatus()==3){
				content[i][5]="已支付";
			}
		}
		System.out.println(String.valueOf(content));

		//创建HSSF
		HSSFWorkbook wb = ExcelUtil.getHSSFWorkbook(sheetName, title, content, null);
		System.out.println(wb);

		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			wb.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	/** 
	 * @Title: setResponseHeader 
	 * @Description: 发送响应流方法
	 * @param response
	 * @param fileName  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	public void setResponseHeader(HttpServletResponse response, String fileName) {
		try {
			try {
				fileName = new String(fileName.getBytes(),"ISO8859-1");
			}catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			response.setContentType("application/octet-stream;charset=ISO8859-1");
			response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
			response.addHeader("Pargam", "no-cache");
			response.addHeader("Cache-Control", "no-cache");
		}catch(Exception ex) {
			ex.printStackTrace();
		}
	}

	/** 
	 * @Title: getWord 
	 * @Description: TODO(这里用一句话描述这个方法的作用) 
	 * @param code
	 * @param request
	 * @param response  参数说明 
	 * @return void    返回类型 
	 * @throws 
	 */
	@RequestMapping("getWord")
	public void getWord(@RequestParam("code") String code,HttpServletRequest request,HttpServletResponse response) {
		System.out.println(code);

		// 获取应用的根路径
		String servletContextRealPath = request.getServletContext().getRealPath("");
		// 获取模板文件
		File templateFile = new File(servletContextRealPath + "/wordModel/payBillWordModel.docx");
		FileInputStream in=null;
		try {
			in = new FileInputStream(templateFile);
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		//生成word文件名
		String fileName="烟台凯旋科技有限公司采购付款单"+new Date()+".docx";

		//$替换对象
		PayBill p=payBillService.findPayBill(code);
		Map<String,String> testMap=new HashMap<String, String>();
		testMap.put("code", p.getCode());
		testMap.put("customName", p.getCustomName());
		testMap.put("payTotalMoney", Double.toString(p.getPayTotalMoney()));
		testMap.put("payDate", p.getPayDate().toString());
		if(p.getPayType()==1) {
			testMap.put("payType", "现金");
		}else {
			testMap.put("payType", "转账");
		}
		testMap.put("memo", p.getMemo());

		Double all=0.00;
		//需插入表格替换对象
		List<String[]> testList = new ArrayList<String[]>();
		List<PayBillDetail> payBillDetailList= payBillDetailService.findPayBillDetail(code);
		for(int i=0;i<payBillDetailList.size();i++) {
			PayBillDetail ins=payBillDetailList.get(i);
			testList.add(new String[]{ins.getBillCode(),"应付账目","减少",String.valueOf(ins.getPayMoney()),String.valueOf(ins.getRealMoney()),ins.getMemo()});
			all+=ins.getPayMoney();
		}
		//写入合计金额
		testMap.put("all", String.valueOf(all));
		WorderToNewWordUtils util=new WorderToNewWordUtils();
		XWPFDocument doc= util.changWord(in, testMap, testList, 5);
		//响应到客户端
		try {
			this.setResponseHeader(response, fileName);
			OutputStream os=response.getOutputStream();
			doc.write(os);
			os.flush();
			os.close();
		} catch(Exception e) {
			e.printStackTrace();
		}
	}
}
